<script setup lang='ts'>
import {computed, reactive, ref} from 'vue'
import {NDropdown, useMessage, NModal, NCollapse, NCollapseItem, NButton} from 'naive-ui'
import AvatarComponent from './Avatar.vue'
import TextComponent from './Text.vue'
import {SvgIcon} from '@/components/common'
import {useIconRender} from '@/hooks/useIconRender'
import {t} from '@/locales'
import {useBasicLayout} from '@/hooks/useBasicLayout'
import {copyToClip} from '@/utils/copy'
import axios from "axios";

interface Props {
	dateTime?: string
	text?: string
	inversion?: boolean
	error?: boolean
	loading?: boolean,
	text_src?: string
	latex_src?: string
}

interface Emit {
	(ev: 'regenerate'): void

	(ev: 'delete'): void
}


const props = defineProps<Props>()

const emit = defineEmits<Emit>()

const {isMobile} = useBasicLayout()

const {iconRender} = useIconRender()

const message = useMessage()

const textRef = ref<HTMLElement>()

const asRawText = ref(props.inversion)

const text_src = ref(props.text_src)
const latex_src = ref(props.latex_src)

const messageRef = ref<HTMLElement>()

const options = computed(() => {
	const common = [
		{
			label: t('chat.copy'),
			key: 'copyText',
			icon: iconRender({icon: 'ri:file-copy-2-line'}),
		},
		{
			label: t('common.delete'),
			key: 'delete',
			icon: iconRender({icon: 'ri:delete-bin-line'}),
		},
		{
			label: 'latex🚀docx',
			key: 'docx',
			icon: iconRender({icon: 'ri:file-download-line'}),
		},
		{
			label: 'markdown🚀docx',
			key: 'mdocx',
			icon: iconRender({icon: 'ri:file-download-line'}),
		},
		{
			label: '运行',
			key: 'runs',
			icon: iconRender({icon: 'ri:play-line'}),
		},
	]

	if (!props.inversion) {
		common.unshift({
			label: asRawText.value ? t('chat.preview') : t('chat.showRawText'),
			key: 'toggleRenderType',
			icon: iconRender({icon: asRawText.value ? 'ic:outline-code-off' : 'ic:outline-code'}),
		})
	}

	return common
})


const state = reactive({
	codes: [''], // Default value
	empcode: "",
	empresult: ""
})
const showModalRef = ref(false)

// 创建一个新的处理函数
function getHandleSelect(key: 'runs' | 'mdocx' | 'docx' | 'copyText' | 'delete' | 'toggleRenderType') {
	return function (text: string) {
		switch (key) {
			case 'docx':
				handledocx(text);
				return;
			case 'mdocx':
				mhandledocx(text);
				return;
			case 'copyText':
				handleCopy();
				return;
			case 'toggleRenderType':
				asRawText.value = !asRawText.value;
				return;
			case 'delete':
				emit('delete');
				return;
			case 'runs':
				const codeRegex = /```([\s\S]*?)```/g; // 使用非贪婪匹配来找到所有的代码块
				const matches = [];
				let match;

				while ((match = codeRegex.exec(text)) !== null) {
					// 将代码块分割成行
					let lines = match[1].trim().split('\n');
					// 如果代码块有多行，删除第一行
					if (lines.length > 1) {
						lines.shift();
					}
					// 重新组合代码块并添加到匹配的数组中
					matches.push(lines.join('\n'));
				}
				console.log(state.codes)
				state.codes=matches
				showModalRef.value = true
		}
	};
}



const onPositiveClick = () => {
	message.success('Submit')
	showModalRef.value = false
}

function handleRegenerate() {
	messageRef.value?.scrollIntoView()
	emit('regenerate')
}

//markdown
function mhandledocx(text: any) {
	let id = new Date().getTime().toString()
	axios.post("http://106.53.97.117:2088/mgenertex", {
		"text": text,
		"id": id
	}).then(res => {
		if (res.data.message === "tex file created successfully") {
			axios.post("http://106.53.97.117:2088/mgenerdoc", {
				"id": id
			}).then(res => {
				if (res.data.message === "docx file created successfully") {
					location.href = `http://106.53.97.117:2088/static/m${id}.docx`
				} else {
					alert("失败")
				}
			})
		} else {
			alert("失败")
		}
	})
}


function handledocx(text: any) {
	let id = new Date().getTime().toString()
	axios.post("http://106.53.97.117:2088/genertex", {
		"text": text,
		"id": id
	}).then(res => {
		if (res.data.message === "tex file created successfully") {
			axios.post("http://106.53.97.117:2088/generdoc", {
				"id": id
			}).then(res => {
				if (res.data.message === "docx file created successfully") {
					location.href = `http://106.53.97.117:2088/static/${id}.docx`
				} else {
					alert("失败")
				}
			})
		} else {
			alert("失败")
		}
	})
}

//代码格式转换
async function tosCode(code: any) {
	console.log(code)
	if (state.empcode != "") {
		let id = new Date().getTime().toString()
		axios.post("http://106.53.97.117:2088/hgenertex", {
			"text": state.empcode,
			"id": id
		}).then(res => {
			if (res.data.message === "tex file created successfully") {
				axios.post("http://106.53.97.117:2088/hgenerdoc", {
					"id": id
				}).then(res => {
					if (res.data.message === "docx file created successfully") {
						location.href = `http://106.53.97.117:2088/static/h${id}.docx`
					} else {
						alert("失败")
					}
				})
			} else {
				alert("失败")
			}
		})
	} else {
		console.log("1")
	}

}

//运行代码
async function executeCode(code: any) {
	console.log(code)
	if (state.empcode != "") {
		console.log(state.empcode)
		try {
			const response = await axios.post('http://43.134.63.182:2095/execute', {code: state.empcode});
			// 处理响应，显示结果到终端输出区域
			state.empresult = response.data.result
		} catch (error) {
			// 处理错误
			console.log(error)
		}
	} else {
		try {
			const response = await axios.post('http://43.134.63.182:2095/execute', {code: code});
			// 处理响应，显示结果到终端输出区域
			state.empresult = response.data.result
		} catch (error) {
			// 处理错误
			console.log(error)
		}
	}

}

async function entercode(e: any) {
	if (state.empcode == "") {
		state.empcode = e;
	} else {
		console.log("1")
	}
}

// //代码解释器反馈，关闭模态框，进行再一次请求
// async function tofankui (){
//
// }

async function handleCopy() {
	try {
		await copyToClip(props.text || '')
		message.success('复制成功')
	} catch {
		message.error('复制失败')
	}
}
</script>

<template>
	<n-modal
		style="width: 80%;height: 80%"
		v-model:show="showModalRef"
		:mask-closable="false"
		preset="card"
		content="你确认"
		positive-text="关闭"
		@positive-click="onPositiveClick"
	>
		<template #header>
			<div>代码运行器</div>
		</template>
		<!--		主题内容-->
		<div>
			<br>
			<n-collapse style="height: 600px;overflow-y: scroll;">
				<n-collapse-item
					v-for="(item, index) in state.codes"
					title="代码"
					:name="index.toString()"
					key="index"
					@click="entercode(item)"
				>
					<!--					运行环境-->
					<div>
						<!-- 按钮组 -->
						<div>
							<n-button-group style="position: relative;left: 0;top: 0">
								<n-button @click="executeCode(item)"
													style="border-radius: 0" type="primary">运行
								</n-button>
								<n-button @click="tosCode(item)"
													style="border-radius: 0" type="error">HTML-docx转换
								</n-button>
								<n-button :disabled="true"
													style="border-radius: 0" type="info">反馈
								</n-button>
							</n-button-group>
						</div>
						<textarea v-model="state.empcode"
											style="overflow-y: scroll; padding: 30px;
        width: 100%; height: 300px;
        background-color: #2a4b7d; color: white; border: none; font-family: monospace;"
						></textarea>
						<div>
							<!-- 终端输出 -->
							<div style="background-color: black; color: white; padding: 10px;
							 min-height:300px; overflow-y: auto;max-height: 800px;">
								<!-- 这里是代码执行的结果 -->
								{{ state.empresult }}
							</div>
						</div>
						<!--						右下方设计两个按钮组，为运行  反馈  后面设计个终端样式的终端，用于跑出的结果输出-->
					</div>
				</n-collapse-item>
			</n-collapse>
		</div>
	</n-modal>
	<div
		ref="messageRef"
		class="flex w-full mb-6 overflow-hidden"
		:class="[{ 'flex-row-reverse': inversion }]"
	>
		<div
			class="flex items-center justify-center flex-shrink-0 h-8 overflow-hidden rounded-full basis-8"
			:class="[inversion ? 'ml-2' : 'mr-2']"
		>
			<AvatarComponent :image="inversion"/>
		</div>
		<div class="overflow-hidden text-sm " :class="[inversion ? 'items-end' : 'items-start']">
			<p class="text-xs text-[#b4bbc4]" :class="[inversion ? 'text-right' : 'text-left']">
				{{ dateTime }}
			</p>
			<div
				class="flex items-end gap-1 mt-2"
				:class="[inversion ? 'flex-row-reverse' : 'flex-row']"
			>
				<TextComponent
					ref="textRef"
					:inversion="inversion"
					:error="error"
					:text="text"
					:text_src="text_src"
					:latex_src="latex_src"
					:loading="loading"
					:as-raw-text="asRawText"
				/>
				<div class="flex flex-col">
					<button
						v-if="!inversion"
						class="mb-2 transition text-neutral-300 hover:text-neutral-800 dark:hover:text-neutral-300"
						@click="handleRegenerate"
					>
						<SvgIcon icon="ri:restart-line"/>
					</button>
					<button
						v-if="!inversion"
						class="mb-2 transition text-neutral-300 hover:text-neutral-800 dark:hover:text-neutral-300"
						@click="handledocx(text)"
					>
						<span style="color: red;">
													<SvgIcon icon="ri:download-line"/>
						</span>
					</button>
					<NDropdown
						:trigger="isMobile ? 'click' : 'hover'"
						:placement="!inversion ? 'right' : 'left'"
						:options="options"
						@select="(key) => text !== undefined && getHandleSelect(key)(text)"
					>
						<button class="transition text-neutral-300 hover:text-neutral-800 dark:hover:text-neutral-200">
							<SvgIcon icon="ri:more-2-fill"/>
						</button>
					</NDropdown>
				</div>
			</div>
		</div>
	</div>
</template>
